import React, { Component } from 'react'
import {Avatar, Button, Col, Divider, Form, Icon, Input, Row, Spin} from 'antd'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { createUser, getSocialAccount, userJoinProgram } from '../../action/user'
import { FormattedMessage } from 'react-intl'
import '../../style/registration-editor.css'
import 'antd/dist/antd.css'
import { convertContent } from '../../constant/lang-util'
import {checkValidateCode} from "../../action/verification";
import {CAPTCHA_URL} from "../../constant/captcha-url";
import {guid} from "../../utils/guid";

const FormItem = Form.Item

const formItemLayout = {
  labelCol: {
    xs: {span: 24},
    sm: {span: 6},
  },
  wrapperCol: {
    xs: {span: 24},
    sm: {span: 14},
  },
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 14,
      offset: 6,
    },
  },
}

class RegistrationBodyPage extends Component {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
    loading: false,
    captchaId: guid(),
    captchaUrl: CAPTCHA_URL

  }

  componentWillMount () {
    const param = this.parseUrl(this.props.location.search)
    const jwt = localStorage.getItem("jwt")
    if(this.hasProgramCodeAndJwt(param, jwt)) {
      this.setState({loading: true})
      this.props.userJoinProgram(param)
    }
  }

  hasProgramCodeAndJwt (param, jwt) {
    return param.code && jwt
  }

  parseUrl (url) {
    if (url === '') {
      return {}
    }
    let result = {}
    let query = url.split('?')[1]
    let queryArr = query.split('&')
    queryArr.forEach((item) => {
      let value = item.split('=')[1]
      let key = item.split('=')[0]
      result[key] = value
    })
    return result
  }

  handleSubmit (e) {
    const urlParams = this.parseUrl(this.props.location.search)
    const {socialInfo} = this.props
    const socialAccountId = socialInfo.id
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const {captcha} = values
        const {captchaId} = this.state
        this.props.checkValidateCode(captcha, captchaId, () => {
          (async () => {
            await this.props.register({...values, ...urlParams, socialAccountId})
          })()
        })
        this.setState({captchaId: guid()})
      }
    })
  }

  componentDidMount () {
    const {socialInfo} = this.props
    if (socialInfo.id) {
      this.props.getSocialAccount(socialInfo.id)
    }

  }

  handleConfirmBlur = (e) => {
    const value = e.target.value
    this.setState({confirmDirty: this.state.confirmDirty || !!value})
  }

  checkPassword = (rule, value, callback) => {
    const form = this.props.form
    if (value && value !== form.getFieldValue('password')) {
      callback('Two passwords that you enter is inconsistent!')
    } else {
      callback()
    }
  }

  checkConfirm = (rule, value, callback) => {
    const form = this.props.form
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], {force: true})
    }
    callback()
  }

  getProgramCode () {
    const param = this.props.location.search
    return param.includes('code') ? param : ''
  }

  handleImg () {
    this.setState({captchaId: guid()})
  }

  render () {
    const {loading, captchaUrl, captchaId} = this.state
    const url = captchaUrl + '/' + captchaId
    const {getFieldDecorator} = this.props.form
    const {socialInfo} = this.props
    const isSocialRegister = !!socialInfo.id
    const programCode = this.getProgramCode()

    return (loading ? <div className='register-loading'>
        <Spin size="large" tip="Loading..." />
      </div>
        : <Col span={8} offset={8} id='register'>
        {
          isSocialRegister ?
            <Row>
              <Col className='register-social-info'>
                <Avatar src={socialInfo.imageUrl}/>
              </Col>
              <Divider>{socialInfo.displayName} <FormattedMessage id='绑定新用户'/></Divider>
            </Row>
            :
            ''
        }
        <Form className="registration-editor-form">
          <FormItem
            {...formItemLayout}
            label={(<span><FormattedMessage id='用户名'/></span>)}
            hasFeedback
            extra={<span className='userName-color'><FormattedMessage id='请务必使用真实姓名'/></span>}
          >
            {getFieldDecorator('username', {
              rules: [{
                required: true,
                message: <FormattedMessage id='用户名中只能包含文字、字母、数字、下划线等'/>,
                validator: (rule, value, callback) => {
                  const reg = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
                  return (reg.test(value) && !!value) ? callback() : callback(true)
                },
                whitespace: true
              }],
            })(<Input/>)}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={(<span><FormattedMessage id='邮箱'/></span>)}
            hasFeedback
          >
            {getFieldDecorator('email', {
              rules: [{
                type: 'email', message: <FormattedMessage id='请输入邮箱'/>,
              }, {
                required: true, message: <FormattedMessage id='邮箱格式不正确'/>,
              }],
            })(
              <Input/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={(<span><FormattedMessage id='密码'/></span>)}
            hasFeedback
          >
            {getFieldDecorator('password', {
              rules: [{
                required: true, message: <FormattedMessage id='请输入密码'/>,
              }, {
                validator: this.checkConfirm,
              }],
            })(
              <Input type="password"/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={(<span><FormattedMessage id='确认密码'/></span>)}
            hasFeedback
          >
            {getFieldDecorator('confirm', {
              rules: [{
                required: true, message: <FormattedMessage id='确认密码'/>,
              }, {
                validator: this.checkPassword,
              }],
            })(
              <Input type="password" onBlur={this.handleConfirmBlur}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={(<span><FormattedMessage id='验证码'/></span>)}
          >
            <Row gutter={8}>
              <Col span={12}>
                {getFieldDecorator('captcha', {
                  rules: [{ required: true, message: <FormattedMessage id='请输入验证码' /> }]
                })(<Input/>)}
              </Col>
              <Col span={12}>
                <img height='32' width='130' style={{cursor: 'pointer'}}
                     src={url}
                     onClick={this.handleImg.bind(this)}
                />
              </Col>
            </Row>
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Col span={12} offset={5}>
              <Button
                type="primary"
                size='large'
                className='register-button'
                htmlType="submit"
                onClick={this.handleSubmit.bind(this)}
              >
                <FormattedMessage id='注册'/>
              </Button>
            </Col>
          </FormItem>

        </Form>
        <Row>
          <div className="login-position"><FormattedMessage id='若已有账户，点击此处'/>
            <a href={`/learn/auth/login${programCode}`}>
              <FormattedMessage id='登录'/></a>
             {programCode ?
               '(' + convertContent('加入训练营') + ')'
              : ''}
          </div>
        </Row>
      </Col>
    )
  }
}

const RegistrationForm = Form.create()(RegistrationBodyPage)
const mapStateToProps = ({registerInfo, socialInfo}) => ({
  registerInfo,
  socialInfo
})
const mapDispatchToProps = dispatch => ({
  register: values => dispatch(createUser(values)),
  getSocialAccount: (id) => dispatch(getSocialAccount(id)),
  checkValidateCode: (validateCode, captchaId, callback) => dispatch(checkValidateCode(validateCode, captchaId, callback)),
  userJoinProgram: (programCode) => dispatch(userJoinProgram(programCode))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(RegistrationForm))
